<?php
/**
 * ?do=list 历史记录
 */
apf_require_controller("Abstract");
apf_require_class("Util_MultiPage");
apf_require_class("Bll_Flow_Info");
apf_require_class("Bll_Hr_Property");
apf_require_class("Security_Api_Crypt_key");
apf_require_class("Bll_Hr_OutInterface");
apf_require_class("Const_Tip");
apf_require_class("Util_Tools");
apf_require_class("Bll_Flow_UserSecurityKey");
class Flow_KeyController extends AbstractController {

    const PAGE_ROWS = 10; //每页显示10条
    const PAGE_NUM_SIZE = 10; //翻页工具条显示10个页码链接

    public function handle_request() {
        $is_admin = $this->check_role_auth();
        if(!$is_admin) {
            $this->show_tips('ERROR_AUTH');
        }
        $data = array();
        $utkl_crypt = Security_Api_Crypt_key::get_instance();
        $params = $this->request->get_parameters();
        if($params['do'] == "list"){
            $data = $this->_handle_request_list($params);
            $data['is_list'] = true;
        }else {
            $data = $this->_handle_request_key();
            $data['is_list'] = false;
        }

        $this->request->set_attribute('data', $data);
        $this->request->set_attribute('params', $params);
        return 'Flow_Key';
    }

    private function _handle_request_list ($params) {
        $data = $search_params = array();

        $search_params = $this->_build_search_params($params);

        $bll_key = new Bll_Flow_UserSecurityKey();

        $search_params['page_size'] = self::PAGE_ROWS;
        $params['p'] = intval($params['p']);
        $search_params['page_num'] = empty($params['p']) ? 1:$params['p'];

        $rs = $bll_key->search_user_list($search_params);
        $data['list'] = $this->_get_other_info($rs['list']);//组装职务和部门信息
        $total = $rs['total'];

        $data['multipage'] = $this->_get_multipage($params,$total);

        return $data;
    }

    private function _get_other_info($list) {
        $result = array();
        if(empty($list)) {return $result;}

        $uids = array();
        foreach($list as $info) {
            $uids[] = $info['user_id'];
        }

        $bll_user = new Bll_Hr_OutInterface();
        $user_infos = $bll_user->get_user_by_ids($uids,1);
        foreach($list as &$info) {
            $info['position_name'] = $user_infos[$info["user_id"]]['job_name'];
            $info['department_name'] = $user_infos[$info["user_id"]]['department_name'];
        }
        return $list;
    }

    private function _get_multipage($params,$total) {

        $url_params = array();
        if(!empty($params['p'])) {
            $url_params['p'] = $params['p'];
        }
        if(!empty($params['user_name'])) {
            $url_params['user_name'] = $params['user_name'];
        }
        if(!empty($params['user_code'])) {
            $url_params['user_code'] = $params['user_code'];
        }
        if(!empty($params['s_time'])) {
            $url_params['s_time'] = $params['s_time'];
        }
        if(!empty($params['e_time'])) {
            $url_params['e_time'] = $params['e_time'];
        }
        $url_params['do'] = "list";
        return Util_MultiPage::multiPage(Flow_Urls::flow_list_key(), $url_params, "", $total, self::PAGE_ROWS, self::PAGE_NUM_SIZE, false, true);
    }

    private function _handle_request_key() {
        $this->api_crypt = Security_Api_Crypt_key::get_instance();
        $data = array();
        //创建密码操作
        if($this->request->is_post_method ()) {
            $params = $this->request->get_parameters();

            if($params['do'] == 'create') {//创建用户密码
                $data = $this->create_user_security($params);

            } else {//使用code查询用户信息页
                $user_code = $params['code'];
                if(empty($user_code)) {
                    return array('error'=>true,'msg'=>Const_Tip::ERROR_PARAM);
                }
                #1. 验证用户的正确性
                $bll_user = new Bll_Hr_OutInterface();
                $user_info = $bll_user->get_user_info_by_code($user_code);
                if(empty($user_info) || empty($user_info['user_name'])) {
                    return array('error'=>true,'msg'=>Const_Tip::ERROR_USER_LOWER_KEY_INFO);
                }
                $user_info = $bll_user->get_user_base_info($user_info['user_id'],1);
                $data = $user_info;
            }
        }
        return $data;
    }

    private function _build_search_params($params) {
        $result = array();
        if(!empty($params['user_name'])) {
            $result['user_name'] = $params['user_name'];
        }
        if(!empty($params['user_code'])) {
            $result['user_code'] = $params['user_code'];
        }

        if(!empty($params['start'])) {
            $result['s_time'] = strtotime($params['start']);
        }
        if(!empty($params['end'])) {
            $result['e_time'] = strtotime($params['end']." 23:59:59");
        }
        return $result;
    }

    public function create_user_security($params) {
        $bll_user = new Bll_Hr_OutInterface();
        $error = $this->_check_params($params);

        if($error) {return array('error'=>true,'msg'=>$error);}

        #1,验证用户信息
        $data = $bll_user->get_user_base_info($params['user_id'],1);
        $data['create_status'] = 1;
        if(empty($data) || empty($data['user_id']) || $data['user_name'] != $params['user_name']) {
            $data['error'] = true;
            $data['msg'] = Const_Tip::ERROR_USER_LOWER_KEY_INFO;
            return $data;
        }

        //验证用户是否有邮箱，没有则不做此操作
        if(empty($data['office_mail'])) {
            $data['error'] = true;
            $data['msg'] = Const_Tip::ERROR_USER_LOWER_KEY_MAIL;
            return $data;
        }

        #2.随机生成8位密文
        $user_rand_key = $this->_create_rand_key(8);

        #3.创建个人用户安全密文
        $is_status = $this->_create_security_miwen($data,$user_rand_key);

        #4.创建成功，将用户的密文发送给用户
        $this->_post_mail($data,$user_rand_key);

        return $data;
    }

    private function _create_rand_key($len = 8) {
        return Util_Tools::make_rand_key($len);
    }

    private function _post_mail($user_info,$user_rand_key) {
        apf_require_class("Tools_SendMail");

        $title = $this->_set_mail_title();
        $body = $this->_set_mail_body($user_info['user_name'],$user_rand_key);

        return Tools_SendMail::get_instance()->send($user_info['office_mail'], $title, $body);
    }

    private function _set_mail_body($uname,$user_rand_key) {
        $rs = "Hi ".$uname.",<br/>";
        $rs .= "<br/>您个人信息的安全密码：{$user_rand_key}<br/>请妥善保存！<br/>";
        return $rs;
    }

    private function _set_mail_title() {
        return "人事系统——个人信息安全密码!";
    }

    /**
     * 创建用户安全密文
     * @param unknown_type $user_id
     */
    private function _create_security_miwen($user_info,$user_rand_key) {
        $bll_key = new Bll_Flow_UserSecurityKey();
        $system_sa = $bll_key->get_system_key();
        if(empty($system_sa)) {return array();}
        $security_miwen = $this->api_crypt->encrypt($system_sa, $user_rand_key);
        return $bll_key->set_user_miwen(array('user_id'=>$user_info['user_id'],'user_name'=>$user_info['user_name'],'user_code'=>$user_info['user_code']),
                $security_miwen);
    }

    /**
     * 参数检测
     */
    private function _check_params($params){
        $error = array();
        #1.验证参数是否完整
        if(empty($params['user_id']) || !is_numeric($params['user_id']) || empty($params['user_name'])) {
            return Const_Tip::ERROR_PARAM;
        }
        return $error;
    }

}